﻿<%@ WebHandler Language="C#" Class="WorkflowStepAmountIterationHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Text;
using System.Linq;
using System.Collections;
/*Description: 工艺期量迭代处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20230616
'Rewriter:
'Rewrite Date:
*/
public class WorkflowStepAmountIterationHandler : IHttpHandler, IRequiresSessionState
{

    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "数据过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetWorkflowIterationInfo": //获取工艺期量迭代数据
                    GetWorkflowIterationInfo(context);
                    break;
                case "GetStepAmountIterationInfo": //获取工序期量迭代数据
                    GetStepAmountIterationInfo(context);
                    break;
                case "GetOtherRevWorkflowInfo": //获取其他版本的工艺数据
                    GetOtherRevWorkflowInfo(context);
                    break;
                case "GetStepAmountIterationTimeData": //获取计算后的工序期量数据
                    GetStepAmountIterationTimeData(context);
                    break;
                case "SaveWorkflowAmountIterationInfo": //保存工艺期量迭代数据
                    SaveWorkflowAmountIterationInfo(context);
                    break;
                case "DeleWorkflowAmountIterationInfo": //删除工艺期量迭代数据
                    DeleWorkflowAmountIterationInfo(context);
                    break;
                case "UpdateWorkflowAmountIterationStatus": //更新工艺期量迭代状态
                    UpdateWorkflowAmountIterationStatus(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
    /// <summary>
    /// 获取工艺期量迭代数据
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkflowIterationInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["param"].ToString());
        string[] items = { "productID", "workflowID", "factoryID" };//需要验证的字段
        if (items.Where(p => string.IsNullOrWhiteSpace(param[p])).Count() == 3)
        {
            result.Result = false; result.Message = "至少输入一个查询条件";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //查询
        StringBuilder sql = new StringBuilder();
        sql.AppendLine(@"SELECT wi.*,pb.productname || ':' || p.productrevision productnameandrev,pb.productname,
                        wb1.workflowname || ':' || w1.workflowrevision referworkflownameandrev,wb1.workflowname referworkflowname,
                        wb2.workflowname || ':' || w2.workflowrevision renewworkflownameandrev,wb2.workflowname renewworkflowname,
                        f.factoryname,DECODE(wi.status,0,'已创建',1,'已提交',2,'已审核',3,'已退回','未知状态') statusname,
                        e.fullname createempname,ee.fullname modifyempname
                        FROM WorkflowAmountIterationInfo wi
                        LEFT JOIN product p ON p.productid = wi.productid
                        LEFT JOIN productbase pb ON pb.productbaseid = p.productbaseid
                        LEFT JOIN workflow w1 ON w1.workflowid = wi.referworkflowid
                        LEFT JOIN Workflowbase wb1 ON wb1.workflowbaseid = w1.workflowbaseid
                        LEFT JOIN workflow w2 ON w2.workflowid = wi.renewworkflowid
                        LEFT JOIN Workflowbase wb2 ON wb2.workflowbaseid = w2.workflowbaseid
                        LEFT JOIN factory f ON f.factoryid = wi.factoryid
                        LEFT JOIN employee e ON e.employeeid = wi.createemployeeid
                        LEFT JOIN employee ee ON ee.employeeid = wi.modifyemployeeid
                        WHERE 1=1 ");
        if (!string.IsNullOrWhiteSpace(param["productID"]))
        {
            sql.AppendFormat(" AND wi.productid = '{0}'", param["productID"]);
        }
        if (!string.IsNullOrWhiteSpace(param["workflowID"]))
        {
            sql.AppendFormat(" AND wi.referworkflowid = '{0}'", param["workflowID"]);
        }
        if (!string.IsNullOrWhiteSpace(param["factoryID"]))
        {
            sql.AppendFormat(" AND wi.factoryid = '{0}'", param["factoryID"]);
        }
        if (!string.IsNullOrWhiteSpace(param["status"]))
        {
            sql.AppendFormat(" AND wi.status = {0}", int.Parse(param["status"]));
        }
        sql.AppendLine(" ORDER BY wi.productid,wi.referworkflowid");
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取工序期量迭代信息（通过工艺期量ID）
    /// </summary>
    /// <param name="context"></param>
    public void GetStepAmountIterationInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string workflowAmountIterationInfoID = context.Request["workflowAmountIterationInfoID"].ToString();
        //查询
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT ws.workflowstepname,ws.workflowstepid,s.factoryid,wc.workcentername,t.teamname,
                        f.factoryname,st.spectypename,ws.makeempcounts,ws.chargingqty,s.ncnumber,DECODE(s.ncnumber,'1','是','') ncnumbername,
                        CASE WHEN NVL(ws.controlcode,s.controlcode) = 'LY05' THEN '外委序' WHEN s.factoryid <> w.factoryid THEN '转工序'
                        WHEN s.lastcheck = '1' AND s.factoryid = w.factoryid THEN '分厂内检序' WHEN s.ncnumber = '1' THEN '数控序' ELSE '普通序' END specType
                        ,sii.stepamountiterationinfoid,sii.preparecycle,sii.preparecycleedit,sii.makecycle,sii.makecycleedit,sii.transfercycle,sii.transfercycleedit
                        ,sii.shipcycle,sii.shipcycleedit,sii.commicycle,sii.commicycleedit,sii.clampingcycle                         
                        FROM StepAmountIterationInfo sii
                        LEFT JOIN workflowstep ws ON ws.workflowstepid = sii.workflowstepid
                        LEFT JOIN workflow w ON w.workflowid = ws.workflowid
                        LEFT JOIN workcenter wc ON wc.workcenterid = ws.workcenterid
                        LEFT JOIN team t ON t.teamid = ws.teamid
                        LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                        LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                        LEFT JOIN factory f ON f.factoryid = s.factoryid
                        LEFT JOIN spectype st ON st.spectypeid = s.spectypeid
                        WHERE sii.workflowamountiterationinfoid = '{0}'
                        ORDER BY ws.sequence", workflowAmountIterationInfoID);
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取计算后的工序的期量迭代数据
    /// </summary>
    /// <param name="context"></param>
    public void GetStepAmountIterationTimeData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "获取成功" };
        Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        string[] items = { "productID", "referworkflowID", "renewWorkflowID", "startDate", "endDate" };//需要验证的字段
        if (items.Where(p => string.IsNullOrWhiteSpace(param[p])).Count() > 0)
        {
            result.Result = false; result.Message = "请填写完整数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (Convert.ToDateTime(param["startDate"]) > Convert.ToDateTime(param["endDate"]))
        {
            result.Result = false; result.Message = "开始日期不能大于结束日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //查询工序数据
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT ws.workflowstepid,ws.workflowstepname,f.factoryname,ws.chargingqty,ws.makeempcounts,wc.workcentername,t.teamname,s.ncnumber,DECODE(s.ncnumber,'1','是','') ncnumbername,
                            CASE WHEN NVL(ws.controlcode,s.controlcode) = 'LY05' THEN '外委序' WHEN s.factoryid <> w.factoryid THEN '转工序'
                            WHEN s.lastcheck = '1' AND s.factoryid = w.factoryid THEN '分厂内检序' WHEN s.ncnumber = '1' THEN '数控序' ELSE '普通序' END specType
                            ,'' preparecycle,'' preparecycleedit,'' makecycle,'' makecycleedit,'' transfercycle,'' transfercycleedit
                            ,'' shipcycle,'' shipcycleedit,'' commicycle,'' commicycleedit,'' clampingcycle
                            FROM  workflow w
                            LEFT JOIN workflowstep ws ON ws.workflowid = w.workflowid
                            LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                            LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                            LEFT JOIN Factory f ON f.factoryid = s.factoryid
                            LEFT JOIN workcenter wc ON wc.workcenterid = ws.workcenterid
                            LEFT JOIN team t ON t.teamid = ws.teamid
                            WHERE w.workflowid = '{0}' ORDER BY ws.sequence", param["referworkflowID"]);
        DataTable dtStep = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        int count = dtStep.Rows.Count;
        for (int i = 0; i < count; i++)
        {
            DataRow item = dtStep.Rows[i];
            switch (item["specType"].ToString())
            {
                case "外委序":
                    item["commicycle"] = GetCommissionTime(item["workflowstepid"].ToString());//外委周期
                    break;
                case "转工序":
                    item["shipcycle"] = GetShipTime(item["workflowstepid"].ToString());//转工周期
                    break;
                case "分厂内检序":
                    if ((i + 1) < count)
                    {
                        Tuple<int, int> res = GetSelfCheckStepTime(item["workflowstepid"].ToString(), dtStep.Rows[i + 1]["specType"].ToString());
                        item["preparecycle"] = res.Item1;//准备时间
                        item["transfercycle"] = res.Item2;//转运时间
                    }
                    break;
                case "数控序":
                    break;
                case "普通序":
                    if ((i + 1) < count)
                    {
                        Tuple<int, int, int> res = GetCommonStepTime(item["workflowstepid"].ToString(), dtStep.Rows[i + 1]["specType"].ToString());
                        item["preparecycle"] = res.Item1;//准备时间
                        item["makecycle"] = res.Item2;//加工时间
                        item["transfercycle"] = res.Item2;//转运时间
                    }
                    break;
                default:
                    break;
            }
        }
        result.DBTable = dtStep;
        result.ReturnData = dtStep.AsEnumerable().Sum(p => string.IsNullOrWhiteSpace(p["preparecycle"].ToString()) ? 0 : int.Parse(p["preparecycle"].ToString()));
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取外委序的外委周期
    /// </summary>
    /// <remarks>外委周期（d）计算逻辑：外委转回日期减去外委转出日期</remarks>
    /// <param name="workflowStepID"></param>
    /// <returns></returns>
    private int GetCommissionTime(string workflowStepID)
    {
        int commiCycle = 0;
        string sql = string.Format(@"SELECT min(cc.outdate) outdate,max(cc.indate) indate FROM containercommidetail cm 
                        LEFT JOIN containercommissioning cc ON cc.containercommissioningid = cm.containercommissioningid
                        WHERE cm.workflowstepid = '{0}' AND cc.isuse = 0 AND cm.isuse = 0
                        GROUP BY cm.workflowstepid", workflowStepID);
        DataTable dtCommi = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtCommi.Rows.Count > 0)
        {
            DataRow dr = dtCommi.Rows[0];
            if (!string.IsNullOrWhiteSpace(dr["indate"].ToString()) && !string.IsNullOrWhiteSpace(dr["outdate"].ToString()))
            {
                TimeSpan ts = Convert.ToDateTime(dr["indate"].ToString()).Subtract(Convert.ToDateTime(dr["outdate"].ToString()));
                commiCycle = ts.Days;
            }
        }
        return commiCycle;
    }

    /// <summary>
    /// 获取转工序的转工周期
    /// </summary>
    /// <remarks>
    /// 转工周期（h）计算逻辑：转工转回日期减去转工发出日期
    /// </remarks>
    /// <param name="workflowStepID">工序ID</param>
    /// <returns></returns>
    private int GetShipTime(string workflowStepID)
    {
        int shipCycle = 0;
        string sql = string.Format(@"SELECT MIN(csr.senddate) senddate,MAX(csv.completedate) completedate FROM containershiprecordstep csrs 
                                    LEFT JOIN containershiprecord csr ON csr.containershiprecordid = csrs.containershiprecordid
                                    LEFT JOIN containershiprecive csv ON csv.containershiprecordid = csr.containershiprecordid
                                    WHERE csr.isuse =0 AND csv.isuse =0 AND csrs.workflowstepid = '{0}'
                                    GROUP BY csrs.workflowstepid", workflowStepID);
        DataTable dtCommi = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtCommi.Rows.Count > 0)
        {
            DataRow dr = dtCommi.Rows[0];
            if (!string.IsNullOrWhiteSpace(dr["completedate"].ToString()) && !string.IsNullOrWhiteSpace(dr["senddate"].ToString()))
            {
                TimeSpan ts = Convert.ToDateTime(dr["completedate"].ToString()).Subtract(Convert.ToDateTime(dr["senddate"].ToString()));
                int dayHours = ts.Days * 24;
                shipCycle = dayHours + ts.Hours;
            }
        }
        return shipCycle;
    }

    /// <summary>
    /// 获取分厂内检序的准备时间、转运时间
    /// </summary>
    /// <remarks>
    /// -- 准备时间（min）：下序报工时间-本序派工时间为上限
    /// -- 转运时间（min）：如果下序是数控序，计算下序任务下达到DNC/MDC时间-本工序工人报工时间（含检验周期）；下工序是普通序，计算下工序报工-本工序检验
    /// </remarks>
    /// <param name="workflowStepID">工序ID</param>
    /// <param name="workflowStepID">下一道工序类型</param>
    /// <returns></returns>
    private Tuple<int, int> GetSelfCheckStepTime(string workflowStepID, string nextStepType)
    {
        int prepareCycle = 0, TransferCycle = 0;
        //计算准备时间
        string sql = string.Format(@"SELECT MIN(csd.createdate) disdate,MAX(csw.createdate) reportdate FROM workflowstep ws 
                                     LEFT JOIN containerstepdispatch csd ON csd.workflowstepid = ws.workflowstepid AND csd.isuse = 0
                                     LEFT JOIN workflowstep nxws ON nxws.workflowid = ws.workflowid AND nxws.sequence = (ws.sequence+1)
                                     LEFT JOIN containerstepworkreport csw ON csw.workflowstepid = nxws.workflowstepid AND csw.isuse = 0
                                     WHERE ws.workflowstepid = '{0}'
                                     GROUP BY ws.workflowstepid", workflowStepID);
        DataTable dtPrepare = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtPrepare.Rows.Count > 0)
        {
            DataRow dr = dtPrepare.Rows[0];
            if (!string.IsNullOrWhiteSpace(dr["reportdate"].ToString()) && !string.IsNullOrWhiteSpace(dr["disdate"].ToString()))
            {
                TimeSpan ts = Convert.ToDateTime(dr["reportdate"].ToString()).Subtract(Convert.ToDateTime(dr["disdate"].ToString()));
                int dayMinutes = ts.Days * 24 * 60;//相隔天数的分钟数
                int hourMinutes = ts.Hours * 60;//相隔小时数的分钟数
                prepareCycle = dayMinutes + hourMinutes + ts.Minutes;
            }
        }
        //计算转运时间
        sql = "";
        if (nextStepType == "数控序")
        {
            sql = "";
        }
        else if (nextStepType == "普通序")
        {
            sql = string.Format(@"SELECT MIN(cci.createdate) checkdate,MAX(csw.createdate) reportdate FROM workflowstep ws 
                                    LEFT JOIN containercheckinfo cci ON cci.workflowstepid = ws.workflowstepid AND cci.isuse = 0
                                    LEFT JOIN workflowstep nxws ON nxws.workflowid = ws.workflowid AND nxws.sequence = (ws.sequence+1)
                                    LEFT JOIN containerstepworkreport csw ON csw.workflowstepid = nxws.workflowstepid AND csw.isuse = 0
                                    WHERE ws.workflowstepid = '{0}'
                                    GROUP BY ws.workflowstepid", workflowStepID);
        }
        if (!string.IsNullOrWhiteSpace(sql))
        {
            DataTable dtTransfer = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtTransfer.Rows.Count > 0)
            {
                DataRow dr = dtTransfer.Rows[0];
                if (!string.IsNullOrWhiteSpace(dr["reportdate"].ToString()) && !string.IsNullOrWhiteSpace(dr["checkdate"].ToString()))
                {
                    TimeSpan ts = Convert.ToDateTime(dr["reportdate"].ToString()).Subtract(Convert.ToDateTime(dr["checkdate"].ToString()));
                    int dayMinutes = ts.Days * 24 * 60;//相隔天数的分钟数
                    int hourMinutes = ts.Hours * 60;//相隔小时数的分钟数
                    TransferCycle = dayMinutes + hourMinutes + ts.Minutes;
                }
            }
        }
        return new Tuple<int, int>(prepareCycle, TransferCycle);
    }

    /// <summary>
    /// 获取普通工序的准备时间、加工时间、转运时间
    /// </summary>
    /// <remarks>
    /// -- 准备时间（min）：下序报工时间-本序派工时间为上限
    /// -- 加工时间（min）：（下序报工时间-本序派工时间）/数量为上限
    /// -- 转运时间（min）：如果下序是数控序，计算下序任务下达到DNC/MDC时间-本工序工人报工时间（含检验周期）；下工序是普通序计算下工序报工-本工序检验
    /// </remarks>
    /// <param name="workflowStepID">工序ID</param>
    /// <param name="nextStepType">下一道工序类型</param>
    /// <returns></returns>
    private Tuple<int, int, int> GetCommonStepTime(string workflowStepID, string nextStepType)
    {
        int prepareCycle = 0, makeCycle = 0, TransferCycle = 0;//准备时间，加工时间，转运时间
        //计算准备时间、加工时间
        string sql = string.Format(@"SELECT MIN(csd.createdate) disdate,MAX(csw.createdate) reportdate,max(csw.qty) qty FROM workflowstep ws 
                                     LEFT JOIN containerstepdispatch csd ON csd.workflowstepid = ws.workflowstepid AND csd.isuse = 0
                                     LEFT JOIN workflowstep nxws ON nxws.workflowid = ws.workflowid AND nxws.sequence = (ws.sequence+1)
                                     LEFT JOIN containerstepworkreport csw ON csw.workflowstepid = nxws.workflowstepid AND csw.isuse = 0
                                     WHERE ws.workflowstepid = '{0}'
                                     GROUP BY ws.workflowstepid", workflowStepID);
        DataTable dtPrepare = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtPrepare.Rows.Count > 0)
        {
            DataRow dr = dtPrepare.Rows[0];
            if (!string.IsNullOrWhiteSpace(dr["reportdate"].ToString()) && !string.IsNullOrWhiteSpace(dr["disdate"].ToString()))
            {
                TimeSpan ts = Convert.ToDateTime(dr["reportdate"].ToString()).Subtract(Convert.ToDateTime(dr["disdate"].ToString()));
                int dayMinutes = ts.Days * 24 * 60;//相隔天数的分钟数
                int hourMinutes = ts.Hours * 60;//相隔小时数的分钟数
                prepareCycle = dayMinutes + hourMinutes + ts.Minutes;//准备时间
                double makes = Convert.ToDouble(prepareCycle / int.Parse(dr["qty"].ToString()));
                makeCycle = Convert.ToInt32(Math.Ceiling(makes)); //加工时间
            }
        }
        //计算转运时间
        sql = "";
        if (nextStepType == "数控序")
        {
            sql = "";
        }
        else if (nextStepType == "普通序")
        {
            sql = string.Format(@"SELECT MIN(cci.createdate) checkdate,MAX(csw.createdate) reportdate FROM workflowstep ws 
                                    LEFT JOIN containercheckinfo cci ON cci.workflowstepid = ws.workflowstepid AND cci.isuse = 0
                                    LEFT JOIN workflowstep nxws ON nxws.workflowid = ws.workflowid AND nxws.sequence = (ws.sequence+1)
                                    LEFT JOIN containerstepworkreport csw ON csw.workflowstepid = nxws.workflowstepid AND csw.isuse = 0
                                    WHERE ws.workflowstepid = '{0}'
                                    GROUP BY ws.workflowstepid", workflowStepID);
        }
        if (!string.IsNullOrWhiteSpace(sql))
        {
            DataTable dtTransfer = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtTransfer.Rows.Count > 0)
            {
                DataRow dr = dtTransfer.Rows[0];
                if (!string.IsNullOrWhiteSpace(dr["reportdate"].ToString()) && !string.IsNullOrWhiteSpace(dr["checkdate"].ToString()))
                {
                    TimeSpan ts = Convert.ToDateTime(dr["reportdate"].ToString()).Subtract(Convert.ToDateTime(dr["checkdate"].ToString()));
                    int dayMinutes = ts.Days * 24 * 60;//相隔天数的分钟数
                    int hourMinutes = ts.Hours * 60;//相隔小时数的分钟数
                    TransferCycle = dayMinutes + hourMinutes + ts.Minutes;
                }
            }
        }
        return new Tuple<int, int, int>(prepareCycle, makeCycle, TransferCycle);
    }

    /// <summary>
    /// 获取其他版本的工艺
    /// </summary>
    /// <param name="context"></param>
    public void GetOtherRevWorkflowInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string workflowID = context.Request["workflowID"].ToString();
        //查询
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT wb.workflowname || '' || w.workflowrevision workflownameandrev,w.workflowid
                            FROM workflow ww
                            LEFT JOIN workflowbase wb ON wb.workflowbaseid = ww.workflowbaseid
                            LEFT JOIN Workflow w ON w.workflowbaseid = wb.workflowbaseid
                            WHERE ww.workflowid = '{0}' AND w.workflowid != '{0}'", workflowID);
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存工艺的期量迭代数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveWorkflowAmountIterationInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "保存成功" };
        Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        string[] items = { "productID", "referworkflowID", "renewWorkflowID", "startDate", "endDate" };//需要验证的字段
        if (items.Where(p => string.IsNullOrWhiteSpace(param[p])).Count() > 0)
        {
            result.Result = false; result.Message = "请填写完整数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (Convert.ToDateTime(param["startDate"]) > Convert.ToDateTime(param["endDate"]))
        {
            result.Result = false; result.Message = "开始日期不能大于结束日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DataTable dtStep = JsonConvert.DeserializeObject<DataTable>(context.Request["stepDatas"].ToString());
        if (dtStep.Rows.Count == 0)
        {
            result.Result = false; result.Message = "没有工序数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        ArrayList sqlList = new ArrayList();
        string sql = string.Empty;
        //sql = string.Format(@"SELECT 1 FROM WorkflowAmountIterationInfo wi WHERE wi.referworkflowid = '{0}' AND wi.renewworkflowid = '{1}'", param["referworkflowid"].ToString(), param["renewworkflowid"].ToString());
        //if (DatabaseHelper.GetSingle(sql) != null)
        //{
        //    result.Result = false; result.Message = "已存在相同的参考工艺以及相同的更新工艺";
        //    context.Response.Write(JsonConvert.SerializeObject(result));
        //    return;
        //}
        //插入SQL
        string insertSql = @"INSERT INTO WorkflowAmountIterationInfo(Workflowamountiterationinfoid,Productid,Referworkflowid,Renewworkflowid,startdate,enddate,
                             Totaltimelimit,Maintenancetotaltime,Status,Createdate,Createemployeeid,factoryid)VALUES('{0}','{1}','{2}','{3}',to_date('{4}','YYYY-MM-DD'),
                             to_date('{5}','YYYY-MM-DD'),{6},{7},0,SYSDATE,'{8}','{9}')";
        //更新SQL
        string updateSql = @"UPDATE WorkflowAmountIterationInfo wi SET wi.Productid='{0}',wi.Referworkflowid='{1}',wi.Renewworkflowid='{2}',wi.totaltimelimit = '{3}',
                             wi.maintenancetotaltime = '{4}',wi.startdate = to_date('{5}','YYYY-MM-DD'),wi.enddate = to_date('{6}','YYYY-MM-DD'),
                             wi.modifydate=SYSDATE,wi.modifyemployeeid='{7}' WHERE wi.workflowamountiterationinfoid = '{8}'";
        //总工时上限（工序的准备工时合计）
        int totaltimelimit = dtStep.AsEnumerable().Sum(p => string.IsNullOrWhiteSpace(p["Preparecycle"].ToString()) ? 0 : int.Parse(p["Preparecycle"].ToString()));
        //维护总工时（工序的可编辑准备工时合计）
        int maintenanceTotalTime = dtStep.AsEnumerable().Sum(p => string.IsNullOrWhiteSpace(p["Preparecycleedit"].ToString()) ? 0 : int.Parse(p["Preparecycleedit"].ToString()));
        if (maintenanceTotalTime > totaltimelimit)
        {
            result.Result = false; result.Message = "维护总工时大于总工时上限";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //如果没有ID，则插入数据
        if (string.IsNullOrWhiteSpace(param["workflowAmountIterationInfoID"]))
        {
            param["workflowAmountIterationInfoID"] = Guid.NewGuid().ToString();
            sqlList.Add(string.Format(insertSql, param["workflowAmountIterationInfoID"], param["productID"].ToString(), param["referworkflowID"].ToString(), param["renewWorkflowID"].ToString(),
                param["startDate"].ToString(), param["endDate"].ToString(), totaltimelimit, maintenanceTotalTime, m_UserInfo.EmployeeID, m_UserInfo.FactoryID));
        }
        else
        {
            sql = string.Format("SELECT 1 FROM WorkflowAmountIterationInfo wi WHERE wi.workflowamountiterationinfoid = '{0}'", param["workflowAmountIterationInfoID"]);
            if (DatabaseHelper.GetSingle(sql) == null)
            {
                result.Result = false; result.Message = "编辑的数据不存在，请重新查询";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            sqlList.Add(string.Format(updateSql, param["productID"].ToString(), param["referworkflowID"].ToString(), param["renewWorkflowID"].ToString(),
                totaltimelimit, maintenanceTotalTime, Convert.ToDateTime(param["startDate"].ToString()).ToShortDateString(),
                Convert.ToDateTime(param["endDate"].ToString()).ToShortDateString(), m_UserInfo.EmployeeID, param["workflowAmountIterationInfoID"]));
            //删除该工艺期量的所有工序期量历史数据
            sqlList.Add(string.Format("DELETE StepAmountIterationInfo sii WHERE sii.workflowamountiterationinfoid = '{0}'", param["workflowAmountIterationInfoID"]));
        }
        //插入工序期量数据
        insertSql = @"INSERT INTO StepAmountIterationInfo(Stepamountiterationinfoid,Workflowamountiterationinfoid,Workflowstepid,
                      Preparecycle,Preparecycleedit,Makecycle,Makecycleedit,Transfercycle,Transfercycleedit,Shipcycle,Shipcycleedit,
                      Commicycle,Commicycleedit,Clampingcycle,Createdate,Createemployeeid)
                      VALUES('{0}','{1}','{2}',{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},SYSDATE,'{14}')";
        foreach (DataRow item in dtStep.Rows)
        {
            sql = string.Format(insertSql, Guid.NewGuid().ToString(), param["workflowAmountIterationInfoID"], item["Workflowstepid"].ToString(),
                GetFieldNumData(item["Preparecycle"].ToString()), GetFieldNumData(item["Preparecycleedit"].ToString()),
                GetFieldNumData(item["Makecycle"].ToString()), GetFieldNumData(item["Makecycleedit"].ToString()),
                GetFieldNumData(item["Transfercycle"].ToString()), GetFieldNumData(item["Transfercycleedit"].ToString()),
                GetFieldNumData(item["Shipcycle"].ToString()), GetFieldNumData(item["Shipcycleedit"].ToString()),
                GetFieldNumData(item["Commicycle"].ToString()), GetFieldNumData(item["Commicycleedit"].ToString()),
                GetFieldNumData(item["Clampingcycle"].ToString()), m_UserInfo.EmployeeID);
            sqlList.Add(sql);
        }
        if (sqlList.Count > 0)
        {
            DatabaseHelper.ExecuteSqlTran(sqlList);
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 删除工艺期量信息
    /// </summary>
    /// <param name="context"></param>
    public void DeleWorkflowAmountIterationInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "删除成功" };
        DataTable dtWorkflow = JsonConvert.DeserializeObject<DataTable>(context.Request["workflowParam"].ToString());
        if (dtWorkflow.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未选择数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        ArrayList sqlList = new ArrayList();
        foreach (DataRow item in dtWorkflow.Rows)
        {
            string workflowAmountIterationInfoID = item["workflowAmountIterationInfoID"].ToString();
            //删除工艺期量信息
            sqlList.Add(string.Format("DELETE Workflowamountiterationinfo wi WHERE wi.workflowamountiterationinfoid = '{0}'", workflowAmountIterationInfoID));
            //删除工序期量信息
            sqlList.Add(string.Format("DELETE StepAmountIterationInfo sii WHERE sii.workflowamountiterationinfoid = '{0}'", workflowAmountIterationInfoID));
        }
        DatabaseHelper.ExecuteSqlTran(sqlList);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 更新工艺期量信息状态
    /// </summary>
    /// <param name="context"></param>
    public void UpdateWorkflowAmountIterationStatus(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "提交成功" };
        string type = context.Request["type"].ToString();
        DataTable dtWorkflow = JsonConvert.DeserializeObject<DataTable>(context.Request["workflowParam"].ToString());
        if (dtWorkflow.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未选择数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        ArrayList sqlList = new ArrayList();
        foreach (DataRow item in dtWorkflow.Rows)
        {
            string workflowAmountIterationInfoID = item["workflowAmountIterationInfoID"].ToString();
            //更新工艺期量状态
            sqlList.Add(string.Format("UPDATE Workflowamountiterationinfo wi SET wi.Status={0} WHERE wi.workflowamountiterationinfoid = '{1}'", type, workflowAmountIterationInfoID));
        }
        DatabaseHelper.ExecuteSqlTran(sqlList);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取数字类型字段格式化后的数据
    /// </summary>
    /// <param name="fieldValue"></param>
    /// <returns></returns>
    private object GetFieldNumData(string fieldValue)
    {
        if (string.IsNullOrWhiteSpace(fieldValue))
        {
            return "null";
        }
        return int.Parse(fieldValue);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}